<template>
  <div class="ChatPre">
    <c-button quaternary @click="active = true" iconName="InboxTwotone"></c-button>
    <n-drawer height="100%" v-model:show="active" :placement="'top'">
      <n-drawer-content title="预设对话">
        <div class="preNo">已加载{{ filesArray.length }}条预设对话</div>
        <n-data-table :row-class-name="(rowData) => {
          if (selectRow?.id === rowData?.id) {
            return 'hasSelectedRow'
          }
        }" :row-props="rowProps" :columns="columns" :max-height="700" :data="jsonData" :page-count="100" />
        <div class="headerAction">
          <n-pagination :disabled="loading" @update:page="handlePageChange" v-model:page="page"
            :page-count="Math.ceil(filesArray.length / pageSizes + 1)" />
          <n-button @click="createChat" :disabled="!selectRow?.id" type='primary'>从选中预设创建对话</n-button>
        </div>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang='tsx'>
import { createDiscreteApi } from 'naive-ui';
import { v4 } from 'uuid';
import { ref } from 'vue';
const page = ref(1)
const pageSizes = 10
const active = ref(false);
const files = import.meta.glob('/assets/prompt/*.json');
const filesArray = Object.values(files);
const jsonData = ref<any[]>([]);
const loading = ref(false)
const handlePageChange = async (page: number) => {
  loading.value = true
  jsonData.value = []
  const lists = filesArray.slice((page - 1) * pageSizes, (page - 1) * pageSizes + pageSizes)
  for (let i = 0; i < lists.length; i++) {
    jsonData.value.push(await lists[i]())
  }
  loading.value = false
}
handlePageChange(page.value)
const columns = [{
  title: '名称',
  key: 'name',
  render(row: any) {
    return <div class="table-tr">{row.default.definition.project_name}</div>
  }
}, {
  title: '图像',
  key: 'image',
  render(row: any) {
    return <n-image class="table-tr" width="40" src={row.default.definition.avatar} />
  }
}, {
  title: '简介',
  key: 'describe',
  render(row: any) {
    return <div class="table-tr">{row.default.definition.description}</div>
  }
}, {
  title: '标签',
  key: 'tag',
  render(row: any) {
    return row.topics.map((tag: string) => <n-tag key={tag} size="small" type="info">{tag}</n-tag>)
  }
}]
const selectRow = ref()
const rowProps = (row: any) => {
  return {
    onClick: () => {
      selectRow.value = row
    }
  }
}
const { setChat } = chatStore()
const { chatMap, currentChat } = storeToRefs(chatStore())
const { chatSettings } = chatSettingStore()
const systemPrompt =
  [
    'main', 'nsfw', 'dialogueExamples',
    'jailbreak', 'worldInfoAfter'
    , 'worldInfoBefore', 'enhanceDefinitions',
    'charDescription', 'charPersonality', 'scenario',
    'personaDescription'
    // , 'chatHistory'
  ]
const settingsHandler = (settings: any) => {
  const result = {} as Record<string, Message>
  settings.prompt_order[0].order.map((e: any) => {
    if (!e.enabled) return
    let prompt = settings.prompts.find((i: { identifier: any; }) => i.identifier === e.identifier)
    if (systemPrompt.includes(prompt.identifier)) {
      const promptMap: any = {
        charPersonality: 'personality',
        charDescription: 'description',
        personaDescription: 'persona',
        scenario: 'scenario',
        dialogueExamples: 'examples',
        jailbreak: 'jailbreak',
      }
      if (selectRow.value.definition[promptMap[prompt.identifier]]) {
        prompt!.content = selectRow.value.definition[promptMap[prompt.identifier]]
      }
    }
    const id = v4()
    if (prompt!.content || prompt.identifier === 'chatHistory') {
      prompt!.content = prompt!.content?.replace(/{{char}}/g, selectRow.value.default.definition.project_name);
      prompt!.content = prompt!.content?.replace(/{{user}}/g, chatSettings['base'].template['username'].value);
      result[id] = {
        content: prompt!.content,
        role: 'system',
        id,
        identifier: prompt.identifier,
        type: prompt.identifier === 'chatHistory' ? 'history' : 'preChat'
      }
    }
  })
  return result
}
const { message } = createDiscreteApi(["message"]);
const createChat = () => {
  const chatId = setChat().id
  const chat = chatMap.value.get(chatId)
  if (!chatSettings['generate'].template['setting'].value[0]?.url) {
    message.error('请先设置生成配置')
    return
  }
  const settings = JSON.parse(chatSettings['generate'].template['setting'].value[0]?.url)
  const messages = settingsHandler(settings)
  chat!.messages = messages
  chat!.name = selectRow.value.default.definition.project_name
  chat!.user = { name: selectRow.value.default.definition.project_name, avatar: selectRow.value.default.definition.avatar }
  currentChat.value = chatId
  active.value = false
}
</script>

<style lang="scss">
.headerAction {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.preNo {
  margin-bottom: 10px;
}

.hasSelectedRow {
  .n-data-table-td {

    background: #b7ddf36c;
  }
}
</style>